package com.lightkits.wms.domain.retirelib.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.lightkits.common.MessageUtil;
import com.lightkits.common.db.entity.FndOrganizationTl;
import com.lightkits.common.db.entity.FndUomBase;
import com.lightkits.common.db.entity.WmRequestHeader;
import com.lightkits.framework.common.exception.LightKitsBizException;
import com.lightkits.framework.common.logging.Logger;
import com.lightkits.framework.common.logging.LoggerFactory;
import com.lightkits.framework.common.utility.object.ObjectUtil;
import com.lightkits.wms.database.dao.WmsRequestLineMapper;
import com.lightkits.wms.database.dao.WmsWarehouseMapper;
import com.lightkits.wms.database.model.KVCodeModel;
import com.lightkits.wms.database.model.WmRequestLineModel;
import com.lightkits.wms.domain.retirelib.QueryRetireParams;
import com.lightkits.wms.dto.retirelib.RetireListResponseType;
import com.lightkits.wms.dto.retirelib.model.RetireListDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author jing.wei@hand-china.com
 * @date 2019/6/18 15:20
 **/
@Service
public class QueryRetireParamsImpl implements QueryRetireParams {
    private final WmsRequestLineMapper requestLineMapper;
    private final WmsWarehouseMapper mapper;
    private final static Logger LOGGER = LoggerFactory.getLogger(QueryRetireParamsImpl.class);

    @Autowired
    public QueryRetireParamsImpl(WmsRequestLineMapper requestLineMapper,
                                 WmsWarehouseMapper mapper) {
        this.requestLineMapper = requestLineMapper;
        this.mapper = mapper;
    }

    /**
     * 领料单列表查询
     *
     * @param headerId 领料单头ID
     * @return
     */
    @Override
    public RetireListResponseType getRetireList(String headerId) {
        RetireListResponseType responseType = new RetireListResponseType();
        responseType.setSuccessful(true);
        //参数校验
        try {
            if (ObjectUtil.isNullOrEmpty(headerId)) {
                responseType.setSuccessful(false);
                responseType.setMessage(MessageUtil.getSysMessage("NO_OR_INVALID"));
                return responseType;
            }
            WmRequestHeader header = new WmRequestHeader().selectById(headerId);
            if (header == null) {
                responseType.setSuccessful(false);
                responseType.setMessage(MessageUtil.getSysMessage("NO_OR_INVALID"));
                return responseType;
            }
            List<WmRequestLineModel> models = requestLineMapper.getRequestLineByParams(headerId, "");
            responseType.setListDtos(this.convertParams(models));
            responseType.setRequestHeaderId(headerId);
            responseType.setRequestNum(header.getRequestNum());
            FndOrganizationTl tl = new FndOrganizationTl().selectOne(new EntityWrapper()
                    .eq(FndOrganizationTl.ORGANIZATION_ID, header.getOrganizationId()));
            responseType.setOrgName(tl.getOrganizationName());
            List<KVCodeModel> status = mapper.querySysCode("WM_REQUEST_STATUS", header.getProcessStatus(), null);
            responseType.setStatus(status.get(0).getValue());
        } catch (Exception e) {
            LOGGER.error("参数校验错误", e);
            throw new LightKitsBizException(e);
        }
        return responseType;
    }

    /**
     * 参数转换
     *
     * @param lineModels 领料单查询参数
     * @return
     */
    private List<RetireListDto> convertParams(List<WmRequestLineModel> lineModels) {
        List<RetireListDto> listDtos = new ArrayList<>();
        try {
            lineModels.forEach(line -> {
                RetireListDto dto = new RetireListDto();
                dto.setItemId(line.getItemId());
                dto.setItemCode(line.getItemCode());
                dto.setItemDesc(line.getItemDesc());
                dto.setRequestLineId(line.getRequestLineId());
                dto.setWarehouseName(line.getWarehouseName());
                dto.setWmAreaName(line.getWmAreaName());
                dto.setScrappReason(line.getScrappReason());
                dto.setUomCode(line.getUomCode());
                //根据单位的类型保留小数位数
                FndUomBase uomBase = new FndUomBase().selectOne(new EntityWrapper()
                        .eq(FndUomBase.UOM_CODE, line.getUomCode()));
                if (ObjectUtil.isEmpty(uomBase)) {
                    dto.setQty(line.getQty().toString());
                } else {
                    dto.setQty(line.getQty()
                            .setScale(uomBase.getDecimalNumber().intValue()
                                    , BigDecimal.ROUND_HALF_UP).toString());

                }
                listDtos.add(dto);
            });

        } catch (Exception e) {
            LOGGER.error("类型转换失败", e);
            throw new LightKitsBizException(e);
        }
        return listDtos;
    }
}
